package userdisplays;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;

import javax.swing.JTextField;

public class EditableField extends JTextField
	implements MouseListener, FocusListener, KeyListener, Serializable, Editable
{
	private static final long serialVersionUID = 1L;
	private UserPanel panel;
	private String prev = "";
	private boolean editable = true;
	
	public EditableField(UserPanel p, Font font, String s, int width, int height)
	{
		super(s);
		setFont(font);
		panel = p;
		prev = s;
		setPreferredSize(new Dimension(width, height));
		setEditable(false);
		addMouseListener(this);
		addFocusListener(this);
		addKeyListener(this);
	}

	public void keyPressed(KeyEvent e)
	{
		if(!editable)
			return;
	    if (e.getKeyCode() == KeyEvent.VK_ENTER)
	    {
	    	prev = getText();
	    	setEditable(false);
			setCaretPosition(getText().length());
			panel.sendPanel();
	    }
	}

	public void keyReleased(KeyEvent arg0){}
	public void keyTyped(KeyEvent arg0){}

	public void mouseClicked(MouseEvent e)
	{
		if(!editable)
			return;
        getCaret().setVisible(true);
		if(e.getButton() == MouseEvent.BUTTON1)
		{
			prev = getText();
			setEditable(true);
		}
	}

	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}

	public void focusGained(FocusEvent e) {}

	public void focusLost(FocusEvent e)
	{
		if(!editable)
			return;
		setEditable(false);
		setText(prev);
	}

	public void lock()
	{
		editable = false;
	}

	public void unlock()
	{
		editable = true;
	}
}